package com.hsnn.medstgmini.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import nl.captcha.Captcha;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.model.Status;
import com.hsnn.medstgmini.model.Whether;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.sys.service.SysUserManager;

/**
 * @category 登陆|登出
 * @author 单大伟
 * @date 2015-06-10
 */

@Controller
public class LoginController {

	private static final Logger log = Logger.getLogger(LoginController.class);
	

	@Autowired
	private SysUserManager userManager;

	@Autowired
	private HttpSession session;
	
    @Value("#{sysProp['captcha.enable']}")
    private String captchaEnable;
    
    @Value("#{sysProp['system.title']}")
    private String systemTitle;
    
    @Value("#{sysProp['system.host.unit']}")
    private String systemHostUnit;
	/**
	 * @category 跳转登陆页面
	 * @date 2015年6月12日
	 * @return
	 */
	@RequestMapping("/login")
	public String login(HttpServletRequest request) {
		SysUser user = (SysUser) session.getAttribute(Constants.USERINFO);
		if (user != null) {
			return "redirect:index.html";
		}
		request.setAttribute("systemHostUnit", systemHostUnit);
		request.setAttribute("systemTitle", systemTitle);
		return "/login";
	}

	/**
	 * @category 用户登录处理
	 * @author 单大伟
	 * @date 2015-06-10
	 * @param request
	 * @param model
	 * @return String 登录验证成功后跳转到的页面
	 */
	@RequestMapping("/loginAuth")
	public String loginAuth(HttpServletRequest request, Model model) {

		// user pass in parameters
		String username = request.getParameter(Constants.USERNAME);
		String password = request.getParameter(Constants.PASSWORD);
		String answer = request.getParameter(Constants.ANSWER);

		Captcha captcha = (Captcha) session.getAttribute(Captcha.NAME);

		log.info("User [" + username + "] try login!");

		if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
			model.addAttribute("errorMsg", "请输入用户名密码！");
			return "/login";
		}

		if (log.isDebugEnabled()) {
		    log.debug("capt enable = " + captchaEnable);
		}
		
		if (Constants.strTrue.equals(captchaEnable)) {
			if (StringUtils.isBlank(answer)) {
				model.addAttribute("errorMsg", "请输入验证码！");
				return "/login";
			} else if (captcha == null) {
				return "/login";
			} else if (!captcha.getAnswer().equalsIgnoreCase(answer)) {
				model.addAttribute("errorMsg", "验证码不正确！");
				return "/login";
			}
		}

		String encodedPwd = DigestUtils.md5Hex(password);

		HttpSession sessionDemo = request.getSession();
		if (sessionDemo.getAttribute(Constants.USERINFO) != null) {
			log.warn("authentication failed");
			model.addAttribute("errorMsg", "请先退出当前登录用户！");
			return "/login";
		}
		// get user name and pwd from database
		SysUser user = userManager.getUserByUsername(username);
        
		// user pass in empty username and password
		if (user == null) {
			log.warn("empty user");
			model.addAttribute("errorMsg", "用户名或密码不正确！");
			return "/login";
		}
		
		if(user.getStatus()==Status.invalid.getKey()){
			log.warn(" user status is unenabled ");
			model.addAttribute("errorMsg", "该用户已被停用！");
			return "/login";
		}
		if(user.getLocked()==Whether.yes.getKey()){
			log.warn(" user is locked ");
			model.addAttribute("errorMsg", "该用户已被锁定！");
			return "/login";
		}
		if(user.getAcctEnabled()==Whether.no.getKey()){
			log.warn(" user is unacctEnabled ");
			model.addAttribute("errorMsg", "该用户未被激活！");
			return "/login";
		}

		if (encodedPwd.equals(user.getPassword())) {
			log.info("authentication passed");

			HttpSession session = request.getSession(true);
			session.setAttribute(Constants.USERINFO, user);
      
    		
			user.setLoginIp(request.getLocalAddr());
			userManager.saveLoginInfo(user);

			return "redirect:index.html";
		} else {
			log.warn("authentication failed");
			model.addAttribute("errorMsg", "用户名或密码不正确！");
			return "/login";
		}
	}

	/**
	 * @category 用户退出登录处理
	 * @author 单大伟
	 * @date 2015-06-10
	 * @param request
	 * @param model
	 * @return String 退出登录后跳转到的页面
	 */
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request, Model model) {
		HttpSession session = request.getSession();
		if (session != null) {
			session.setAttribute(Constants.USERINFO, null);
			session.invalidate();
		}
		return "redirect:login.html";
	}
}
